package org.simpleframework.mvc.processor.impl;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;

import org.simpleframework.mvc.RequestProcessorChain;
import org.simpleframework.mvc.processor.RequestProcessor;

/**
 * 静态资源请求处理，包括但是不限于图片、css、以及js文件等等
 * @author icanci
 * @date Created in 2021/03/06 21:21
 * @version 1.0
 */
@Slf4j
public class StaticResourceRequestProcessor implements RequestProcessor {
    public static final String DEFAULT_TOMCAT_SERVLET = "default";
    public static final String STATIC_RESOURCE_PREFIX = "/static/";
    /**
     * tomcat默认请求派发器RequestDispatcher的名称
     */
    RequestDispatcher          defaultDispatcher;

    /**
     * 构造方法
     * @param servletContext Servlet上下文
     */
    public StaticResourceRequestProcessor(ServletContext servletContext) {
        this.defaultDispatcher = servletContext.getNamedDispatcher(DEFAULT_TOMCAT_SERVLET);
        if (this.defaultDispatcher == null) {
            throw new RuntimeException("There is no default tomcat servlet");
        }
        log.info("The default servlet for static resource is {}", DEFAULT_TOMCAT_SERVLET);
    }

    /**
     * process
     * @param requestProcessorChain 请求链
     * @return 是否继续执行
     * @throws Exception
     */
    @Override
    public boolean process(RequestProcessorChain requestProcessorChain) throws Exception {
        //1.通过请求路径判断是否是请求的静态资源 webapp/static
        if (isStaticResource(requestProcessorChain.getRequestPath())) {
            //2.如果是静态资源，则将请求转发给default servlet处理
            // TODO 这里出现了谷歌浏览器不渲染图片的情况
            defaultDispatcher.forward(requestProcessorChain.getRequest(), requestProcessorChain.getResponse());
            return false;
        }
        return true;
    }

    /**
     * 通过请求路径前缀（目录）是否为静态资源 /static/
     * @param path 请求路径
     * @return 返回是否可访问
     */
    private boolean isStaticResource(String path) {
        System.out.println("path:" + path);
        return path.startsWith(STATIC_RESOURCE_PREFIX);
    }
}